// ============================== 导入依赖 ============================== //

import CORE from '@root/【CORE】'
import TRANS from '../TRANS'

import { TokenReq as OneClass } from '@demo/proto/user/demo_user_pb'

import { DemoUserPromiseClient as Client } from '@demo/proto/user/demo_user_grpc_web_pb'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 单项 —————————————————————————————— //

  async getUser(one, name = '用户') {
    const DTO = CORE.grpcDTO(OneClass, one)
    const resp = await CORE.grpc(TRANS.transTip(name), CLIENT, 'tokenUser', DTO)
    return { ...resp.content, menuTree: transMenu(MENU) }
  },
}

// ============================== 内部变量 ============================== //

const MENU = [
  {
    id: '88',
    name: '示例页面',
    project: '示例',
    children: [
      {
        id: '8810',
        name: '示例角色',
        catalogue: 'DemoRole',
        openType: 1,
        icon: 'el-icon-reading',
      },
      {
        id: '8820',
        name: '示例用户',
        catalogue: 'DemoUser',
        openType: 1,
        icon: 'el-icon-user',
      },
      {
        id: '8870',
        name: '示例组件',
        catalogue: 'DemoComponent',
        openType: 1,
        icon: 'el-icon-view',
      },
      {
        id: '8880',
        name: '示例图表',
        catalogue: 'DemoChart',
        openType: 1,
        icon: 'el-icon-s-data',
      },
      {
        id: '8888',
        name: '未知菜单',
        catalogue: 'DemoUnknow',
        openType: 1,
        icon: 'el-icon-attract',
      },
    ],
  },

  {
    id: '99',
    name: '内核页面',
    project: '示例',
    children: [
      {
        id: '990',
        name: '内核示例',
        icon: 'el-icon-menu',
        children: [
          {
            id: '9910',
            name: '示例角色',
            catalogue: 'CoreDemo_DemoRole',
            openType: 1,
          },
          {
            id: '9920',
            name: '示例用户',
            catalogue: 'CoreDemo_DemoUser',
            openType: 1,
          },
          {
            id: '9980',
            name: '示例组件',
            catalogue: 'CoreDemo_DemoComponent',
            openType: 1,
          },
          {
            id: '9990',
            name: '示例图表',
            catalogue: 'CoreDemo_DemoChart',
            openType: 1,
          },
          {
            id: '9999',
            name: '未知菜单',
            catalogue: 'CoreDemo_DemoUnknow',
            openType: 1,
          },
        ],
      },
    ],
  },
]

// ============================== 转换方法 ============================== //

const transMenu = (tree) => {
  // 排序
  tree.sort((a, b) => a.sort - b.sort)

  tree.forEach((item) => {
    const children = item.children || []
    item.children = children

    // 先递归所有子节点
    transMenu(children)

    // 以 catalogue 存储该菜单下的第一个路由目录
    item.catalogue = item.catalogue || (children[0] || {}).catalogue
  })

  return tree
}
